layui.use(['table', 'HttpRequest', 'func', 'form', 'laydate', 'tree'], function () {
    var $ = layui.$;
    var HttpRequest = layui.HttpRequest;
    var tree = layui.tree;
    var form = layui.form;

    var requestList = new HttpRequest(Feng.ctxPath + "/works/list", 'get');
    var resultList = requestList.start();
    console.log(resultList.data);
    // 按 workDept 分组数据
    var groupedData = {};
    if (requestList && resultList.data) {
        resultList.data.forEach(function(item) {
            if (!groupedData[item.workDept]) {
                groupedData[item.workDept] = {
                    workDept: item.workDept,
                    workDeptName: item.workDeptName,
                    works: []
                };
            }
            groupedData[item.workDept].works.push(item);
        });
    }


    var request = new HttpRequest(Feng.ctxPath + "/works/workConfig", 'get');
    var result = request.start();
    var data = result.data;
    // 显示投票时间
    $('#beginTime').text(data.begin);
    $('#endTime').text(data.end);

    // 检查投票时间
    // 检查投票时间
    var checkVoteTime = function() {
        var now = new Date();
        var begin = new Date(data.begin);
        var end = new Date(data.end);

        if (now < begin) {
            layer.msg('投票还未开始，开始时间：' + data.begin);
            $('#beginTime, #endTime, #state').css('color', 'rgb(218,217,217)');  // 默认颜色
            $("#state").html("（未开始）")
            return false;
        }
        if (now > end) {
            layer.msg('投票已结束，结束时间：' + data.end);
            $('#beginTime, #endTime, #state').css('color', '#FF5722');  // 结束显示红色
            $("#state").html("（已结束）")
            return false;
        }
        $('#beginTime, #endTime, #state').css('color', '#009688')
        $("#state").html("（进行中）");  // 进行中显示绿色
        return true;
    }

    // 计数器
    var voteCount = {
        bureau: 0,
        team: 0
    };
    var maxCount = data.maxNum ? data.maxNum : 12

    $("#maxCount, .vote-rules-max-num").html(maxCount)
    // 渲染投票选项
    var renderVoteOptions = function() {
        var html = '';
        // 动态生成部门容器
        Object.values(groupedData).forEach(function(dept) {
            html += `
                <div class="vote-section">
                    <div class="section-title">
                        ${dept.workDeptName}作品
                        <span class="vote-count">已选择：<span id="count_${dept.workDept}" class="dept-count" data-dept="${dept.workDept}">0</span> 个</span>
                    </div>
                    <div class="dept-works" id="works_${dept.workDept}"></div>
                </div>
            `;
        });

        $('#voteContainer').html(html);

        // 渲染各部门作品
        Object.values(groupedData).forEach(function(dept) {
            var deptHtml = '';
            dept.works.forEach(function(work) {
                let title = work.workTitle + "（" + work.workAuthor +"）"
                deptHtml += `
                    <div class="layui-input-inline">
                        <input type="checkbox" name="vote" 
                               value="${work.workId}"
                               data-dept="${dept.workDept}"
                               title="${title}" 
                               lay-skin="primary" 
                               lay-filter="voteItem">
                    </div>
                `;
            });
            $(`#works_${dept.workDept}`).append(deptHtml);
        });

        form.render('checkbox');
    }

    // 监听复选框点击
    form.on('checkbox(voteItem)', function(data) {
        var checkedCount = $('input[name="vote"]:checked').length;
        $('#voteCount').text(checkedCount);

        // 更新部门计数
        Object.values(groupedData).forEach(function(dept) {
            var deptCheckedCount = $(`input[name="vote"][data-dept="${dept.workDept}"]:checked`).length;
            $(`#count_${dept.workDept}`).text(deptCheckedCount);
        });
        if (checkedCount > maxCount) {
            data.elem.checked = false;
            layer.msg('最多只能选择' + maxCount + '个作品');
            form.render('checkbox');
            $('#voteCount').text(maxCount);
        }

        checkSubmitStatus();
    });

    // 检查提交按钮状态
    var checkSubmitStatus = function() {
        var checkedCount = $('input[name="vote"]:checked').length;
        var canSubmit = checkedCount == maxCount;
        $('#submitVote').prop('disabled', !canSubmit)
            .toggleClass('layui-btn-disabled', !canSubmit);
    }


    $('#submitVote').on('click', function(){
        if ($(this).hasClass('layui-btn-disabled')) return;
        if (!checkVoteTime()) return;

        var votes = [];
        $('input[name="vote"]:checked').each(function() {
            votes.push($(this).val());
        });

        console.log("votes:", votes);
        // 提交投票请求
        // 使用jQuery ajax发送请求
        $.ajax({
            url: Feng.ctxPath + "/voteHistory/vote",
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(votes),
            success: function(result) {
                if (result.success) {
                    layer.msg('投票成功！', {icon: 1});
                    // 禁用所有复选框
                    $('input[name="vote"]').prop('disabled', true);
                    form.render('checkbox');
                    // 隐藏提交按钮
                    $('#submitVote').hide();
                } else {
                    layer.msg(result.message || '投票失败，请重试', {icon: 2});
                }
            },
            error: function() {
                layer.msg('网络错误，请重试', {icon: 2});
            }
        });
    });

    // 初始化
    renderVoteOptions();
    let flag = checkVoteTime();
    if (flag) {
        $("#submitVote").show();
    }

});